<?php
class ContactController extends Controller {

	private function loadModel($id){
		$model= Contact::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

    public function actionIndex(){
		$model= new Contact('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Contact']))
			$model->attributes = $_GET['Contact'];

		$this->render('index', array(
			'model' => $model
		));
    }

    public function actionCreate(){
		$model = new Contact();
		$this->ajaxValidate($model);
		if(Yii::app()->request->isPostRequest && !empty($_POST['Contact'])){
			$model->setAttributes($_POST['Contact'], false);
			if($model->validate()){
				$result = $model->updateContact();
				if($result['success'] === true){
					Yii::app()->user->setFlash('success', $result['msg']);
					$this->redirect(Yii::app()->createUrl('contacts'));
				}
			}
		}
		$this->render('create', array(
			'model' => $model
		));
    }

	public function actionUpdate($id){
		$model = $this->loadModel($id);
		$this->ajaxValidate($model);
		if(Yii::app()->request->isPostRequest && !empty($_POST['Contact'])){
			$model->setAttributes($_POST['Contact'], false);
			if($model->validate()){
				$result = $model->updateContact();
				if($result['success'] === true){
					Yii::app()->user->setFlash('success', $result['msg']);
					$this->redirect(Yii::app()->createUrl('contacts'));
				}
			}
		}
		$this->render('update', array(
			'model' => $model
		));
	}

	public function actionDelete($id){
		$group = $this->loadModel($id)->deleteContact();
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}
}